import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.lang.Math;


/*
 * PCC Tool (Playfield Converter and Compressor)
 * By: Josh Moore
 */
public class Converter {
	
	

	public static void main(String[] args) throws IOException {
		System.out.println("Enter filename here : ");
		// Get file names of input and output
	    Scanner scanIn = new Scanner(System.in);
	    String fileName = scanIn.nextLine()+".txt";
	 
	    System.out.println("Enter input file name:");
	    String input= scanIn.nextLine()+".txt";
	    scanIn.close();            
		
		
		String text = new String();
		String NL = System.getProperty("line.separator");
		Scanner scanner = null;
		BufferedWriter out = null;
		try {
			scanner = new Scanner(new FileInputStream(input));
			out = new BufferedWriter(new FileWriter(fileName));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int currentLineNum=0;
		
		// read in input file and parse X. matrix and generate binary strings
		while (scanner.hasNextLine()) {
			String currentLine = scanner.nextLine();
			String output = new String();
			for (int i = 0; i < currentLine.length(); i++) {
				char c = currentLine.charAt(i);
				if (c == 'X') {
					output += "1";
				}
				if (c == '.') {
					output += "0";
				}
			}
			System.out.println("Begining conversion of Line "+currentLineNum+": "+output );
			// convert binary strings into correct playfield byte data
			text += (binToData(output) + NL);
		}
		try {
			
			out.write(text);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			out.close();
			System.out.println("Finished Conversion");
		}

	}
	
	
	//takes in binary string and returns correct byte data for playfield.
	public static String binToData(String in){
		String result= new String();
		for(int count=0; count<4;count++){
			System.out.println("Starting byteNum: "+count);
			int total=0;
			if(count%2==0){
				int power= 7;
				for(int i=count*8; i<(count*8+8);i++){
					System.out.println("Checking index: "+i);
					char c= in.charAt(i);
					if(c=='1'){
						System.out.println("Found 1, adding 2^"+power);
						total += Math.pow(2,power);
					}
					power--;
				}
			}
			else{
				int power= 0;
				for(int i=count*8; i<(count*8+8);i++){
					System.out.println("Checking index: "+i);
					char c= in.charAt(i);
					if(c=='1'){
						System.out.println("Found 1, adding 2^"+power);
						total += Math.pow(2,power);
					}
					power++;
				}
			}
			System.out.println("Result of byteNum: "+total);
			result+=String.valueOf(total)+',';
			
		}
		return result;
		
		
	}

}
